<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>Vue多页路由与模板解析 | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="Vue,">
  

  <meta name="description" content="一、路由配置1. 跳转  在配置路由前，首先我们要明确一点就是，多页应用中的每个单页都是相互隔离的，即如果你想从 page1 下的路由跳到 page2 下的路由，你无法使用 vue-router 中的方法进行跳转，需要使用原生方法：location.href 或 location.replace  此外为了能够清晰的分辨路由属于哪个单页，我们应该给每个单页路由添加前缀，比如  index 单页：/">
<meta name="keywords" content="Vue">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue多页路由与模板解析">
<meta property="og:url" content="http://blog.poetries.top/2019/06/01/vue-router-and-template-analyse/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="一、路由配置1. 跳转  在配置路由前，首先我们要明确一点就是，多页应用中的每个单页都是相互隔离的，即如果你想从 page1 下的路由跳到 page2 下的路由，你无法使用 vue-router 中的方法进行跳转，需要使用原生方法：location.href 或 location.replace  此外为了能够清晰的分辨路由属于哪个单页，我们应该给每个单页路由添加前缀，比如  index 单页：/">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2018/8/3/164fb7b172500b55">
<meta property="og:updated_time" content="2020-08-15T04:25:31.938Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Vue多页路由与模板解析">
<meta name="twitter:description" content="一、路由配置1. 跳转  在配置路由前，首先我们要明确一点就是，多页应用中的每个单页都是相互隔离的，即如果你想从 page1 下的路由跳到 page2 下的路由，你无法使用 vue-router 中的方法进行跳转，需要使用原生方法：location.href 或 location.replace  此外为了能够清晰的分辨路由属于哪个单页，我们应该给每个单页路由添加前缀，比如  index 单页：/">
<meta name="twitter:image" content="https://user-gold-cdn.xitu.io/2018/8/3/164fb7b172500b55">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、路由配置"><span class="toc-text">一、路由配置</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、模板配置"><span class="toc-text">二、模板配置</span></a></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-vue-router-and-template-analyse" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">Vue多页路由与模板解析</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2019.06.02</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 1.7k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 7分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h2 id="一、路由配置"><a href="#一、路由配置" class="headerlink" title="一、路由配置"></a>一、路由配置</h2><p><strong>1. 跳转</strong></p>
<blockquote>
<p>在配置路由前，首先我们要明确一点就是，多页应用中的每个单页都是相互隔离的，即如果你想从 <code>page1</code> 下的路由跳到 <code>page2</code> 下的路由，你无法使用 <code>vue-router</code> 中的方法进行跳转，需要使用原生方法：<code>location.href</code> 或 <code>location.replace</code></p>
</blockquote>
<p>此外为了能够清晰的分辨路由属于哪个单页，我们应该给每个单页路由添加前缀，比如</p>
<ul>
<li><code>index</code> 单页：<code>/vue/</code></li>
<li><code>page1</code> 单页：<code>/vue/page1/</code></li>
<li><code>page2</code> 单页：<code>/vue/page2/-</code></li>
</ul>
<blockquote>
<p>其中 <code>/vue/</code> 为项目的二级目录，其后的目录代表路由属于哪个单页。因此我们每个单页的路由配置可以像这样</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">/* page1 单页路由配置 */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Vue <span class="keyword">from</span> <span class="string">'vue'</span></span><br><span class="line"><span class="keyword">import</span> Router <span class="keyword">from</span> <span class="string">'vue-router'</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 首页</span></span><br><span class="line"><span class="keyword">const</span> Home = (<span class="function"><span class="params">resolve</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">require</span>.ensure([<span class="string">'../views/home.vue'</span>], () =&gt; &#123;</span><br><span class="line">        resolve(<span class="built_in">require</span>(<span class="string">'../views/home.vue'</span>))</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">Vue.use(Router)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> base = <span class="string">`<span class="subst">$&#123;process.env.BASE_URL&#125;</span>`</span> + <span class="string">'page1'</span>; <span class="comment">// 添加单页前缀</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">new</span> Router(&#123;</span><br><span class="line">    mode: <span class="string">'history'</span>,</span><br><span class="line">    base: base,</span><br><span class="line">    routes: [</span><br><span class="line">        &#123;</span><br><span class="line">            path: <span class="string">'/'</span>,</span><br><span class="line">            name: <span class="string">'home'</span>,</span><br><span class="line">            component: Home</span><br><span class="line">        &#125;,</span><br><span class="line">    ]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>我们通过设置路由的 <code>base</code> 值来为每个单页添加路由前缀，如果是 <code>index</code> 单页我们无需拼接路由前缀，直接跳转至二级目录即可</p>
</blockquote>
<p>那么在单页间跳转的地方，我们可以这样写</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;div id=<span class="string">"app"</span>&gt;</span><br><span class="line">    &lt;div id=<span class="string">"nav"</span>&gt;</span><br><span class="line">      &lt;a @click=<span class="string">"goFn('')"</span>&gt;Index&lt;<span class="regexp">/a&gt; |</span></span><br><span class="line"><span class="regexp">      &lt;a @click="goFn('page1')"&gt;Page1&lt;/</span>a&gt; |</span><br><span class="line">      &lt;a @click=<span class="string">"goFn('page2')"</span>&gt;Page2&lt;<span class="regexp">/a&gt; |</span></span><br><span class="line"><span class="regexp">    &lt;/</span>div&gt;</span><br><span class="line">    &lt;router-view/&gt;</span><br><span class="line">  &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>template&gt;</span><br><span class="line"></span><br><span class="line">&lt;script&gt;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">    methods: &#123;</span><br><span class="line">        goFn(name) &#123;</span><br><span class="line">            location.href = <span class="string">`<span class="subst">$&#123;process.env.BASE_URL&#125;</span>`</span> + name</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>但是为了保持和 <code>Vue</code> 路由跳转同样的风格，我可以对单页之间的跳转做一下封装，实现一个 <code>Navigator</code> 类，类的代码可以查看本文最后的示例，封装完成后我们可以将跳转方法修改为</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">this</span>.$openRouter(&#123;</span><br><span class="line">    name: name, <span class="comment">// 跳转地址</span></span><br><span class="line">    query: &#123;</span><br><span class="line">        text: <span class="string">'hello'</span> <span class="comment">// 可以进行参数传递</span></span><br><span class="line">    &#125;,</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>使用上述 <code>$openRouter</code> 方法我们还需要一个前提条件，便是将其绑定到 Vue 的原型链上，我们在所有单页的入口文件中添加</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Navigator &#125; <span class="keyword">from</span> <span class="string">'../../common'</span> <span class="comment">// 引入 Navigator</span></span><br><span class="line"></span><br><span class="line">Vue.prototype.$openRouter = Navigator.openRouter; <span class="comment">// 添加至 Vue 原型链</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>至此我们已经能够成功模仿 <code>vue-router</code> 进行单页间的跳转，但是需要注意的是因为其本质使用的是 <code>location</code> 跳转，所以必然会产生浏览器的刷新与重载</p>
</blockquote>
<p><strong>2. 重定向</strong></p>
<blockquote>
<p>当我们完成上述路由跳转的功能后，可以在本地服务器上来进行一下测试，你会发现 <code>Index</code> 首页可以正常打开，但是跳转 <code>Page1</code>、<code>Page2</code> 却仍然处于 <code>Index</code> 父组件下，这是因为浏览器认为你所要跳转的页面还是在 <code>Index</code> 根路由下，同时又没有匹配到 <code>Index</code> 单页中对应的路由。这时候我们服务器需要做一次重定向，将下方路由指向对应的 <code>html</code> 文件即可</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">/vue/page1 -&gt; /vue/page1.html</span><br><span class="line">/vue/page2 -&gt; /vue/page2.html</span><br></pre></td></tr></table></figure>
<blockquote>
<p>在 <code>vue.config.js</code> 中，我们需要对 <code>devServer</code> 进行配置，添加 <code>historyApiFallback</code>配置项，该配置项主要用于解决 <code>HTML5 History API</code> 产生的问题，比如其 <code>rewrites</code> 选项用于重写路由</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">/* vue.config.js */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> baseUrl = <span class="string">'/vue/'</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    ...</span><br><span class="line">    </span><br><span class="line">    devServer: &#123;</span><br><span class="line">        historyApiFallback: &#123;</span><br><span class="line">            rewrites: [</span><br><span class="line">                &#123; <span class="attr">from</span>: <span class="keyword">new</span> <span class="built_in">RegExp</span>(baseUrl + <span class="string">'page1'</span>), <span class="attr">to</span>: baseUrl + <span class="string">'page1.html'</span> &#125;,</span><br><span class="line">                &#123; <span class="attr">from</span>: <span class="keyword">new</span> <span class="built_in">RegExp</span>(baseUrl + <span class="string">'page2'</span>), <span class="attr">to</span>: baseUrl + <span class="string">'page2.html'</span> &#125;,</span><br><span class="line">            ]</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>上方我们通过 <code>rewrites</code> 匹配正则表达式的方式将 <code>/vue/page1</code> 这样的路由替换为访问服务器下正确 <code>html</code> 文件的形式，如此不同单页间便可以进行正确跳转和访问了</p>
</blockquote>
<h2 id="二、模板配置"><a href="#二、模板配置" class="headerlink" title="二、模板配置"></a>二、模板配置</h2><p><strong>1. 模板渲染</strong></p>
<blockquote>
<p>这里所说的模板渲染是在我们的 <code>html</code> 模板文件中使用 <code>html-webpack-plugin</code> 提供的 <code>default template</code> 语法进行模板编写，比如</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"utf-8"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">"X-UA-Compatible"</span> <span class="attr">content</span>=<span class="string">"IE=edge"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">"viewport"</span> <span class="attr">content</span>=<span class="string">"width=device-width,initial-scale=1.0"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>模板<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">%</span> <span class="attr">for</span> (<span class="attr">var</span> <span class="attr">chunk</span> <span class="attr">in</span> <span class="attr">htmlWebpackPlugin.files.css</span>) &#123; %&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">%</span> <span class="attr">if</span>(<span class="attr">htmlWebpackPlugin.files.css</span>[<span class="attr">chunk</span>]) &#123;%&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">link</span> <span class="attr">href</span>=<span class="string">"&lt;%= htmlWebpackPlugin.files.css[chunk] %&gt;"</span> <span class="attr">rel</span>=<span class="string">"stylesheet"</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">%&#125;%</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">%</span> &#125; %&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"app"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- built files will be auto injected --&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">%</span> <span class="attr">for</span> (<span class="attr">var</span> <span class="attr">chunk</span> <span class="attr">in</span> <span class="attr">htmlWebpackPlugin.files.js</span>) &#123; %&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">%</span> <span class="attr">if</span>(<span class="attr">htmlWebpackPlugin.files.js</span>[<span class="attr">chunk</span>]) &#123;%&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span> <span class="attr">src</span>=<span class="string">"&lt;%= htmlWebpackPlugin.files.js[chunk] %&gt;"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">%&#125;%</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">%</span> &#125; %&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>以上我们使用模板语法手动获取并遍历 <code>htmlWebpackPlugin</code> 打包后的文件并生成到模板中，其中的 <code>htmlWebpackPlugin</code> 变量是模板提供的可访问变量，其有以下特定数据</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="string">"htmlWebpackPlugin"</span>: &#123;</span><br><span class="line">    <span class="string">"files"</span>: &#123;</span><br><span class="line">        <span class="string">"css"</span>: [ <span class="string">"main.css"</span> ],</span><br><span class="line">        <span class="string">"js"</span>: [ <span class="string">"assets/head_bundle.js"</span>, <span class="string">"assets/main_bundle.js"</span>],</span><br><span class="line">        <span class="string">"chunks"</span>: &#123;</span><br><span class="line">            <span class="string">"head"</span>: &#123;</span><br><span class="line">                <span class="string">"entry"</span>: <span class="string">"assets/head_bundle.js"</span>,</span><br><span class="line">                <span class="string">"css"</span>: [ <span class="string">"main.css"</span> ]</span><br><span class="line">            &#125;,</span><br><span class="line">            <span class="string">"main"</span>: &#123;</span><br><span class="line">                <span class="string">"entry"</span>: <span class="string">"assets/main_bundle.js"</span>,</span><br><span class="line">                <span class="string">"css"</span>: []</span><br><span class="line">            &#125;,</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>我们通过 <code>htmlWebpackPlugin.files</code>可以获取打包输出的 <code>js</code>及 <code>css</code> 文件路径，包括入口文件路径等</li>
<li>需要注意的是如果你在模板中编写了插入对应 <code>js</code> 及 <code>css</code> 的语法，你需要设置 <code>inject</code> 的值为 <code>false</code> 来关闭资源的自动注入</li>
</ul>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">/* utils.js */</span></span><br><span class="line">...</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> conf = &#123;</span><br><span class="line">    entry: filePath, <span class="comment">// page 的入口</span></span><br><span class="line">    template: filePath, <span class="comment">// 模板路径</span></span><br><span class="line">    filename: filename + <span class="string">'.html'</span>, <span class="comment">// 生成 html 的文件名</span></span><br><span class="line">    chunks: [<span class="string">'manifest'</span>, <span class="string">'vendor'</span>,  filename],</span><br><span class="line">    inject: <span class="literal">false</span>, <span class="comment">// 关闭资源自动注入</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">...</span><br></pre></td></tr></table></figure>
<p>否则在页面会引入两次资源，如下图所示</p>
<p><img src="https://user-gold-cdn.xitu.io/2018/8/3/164fb7b172500b55" alt></p>
<p><strong>2. 自定义配置</strong></p>
<blockquote>
<p>在模板渲染中，我们只能够使用 <code>htmlWebpackPlugin</code> 内部的一些属性和方法来进行模板的定制化开发，那么如果遇到需要根据不同环境来引入不同资源，同时不同模板间的配置还可能不一样的需求情况的话，我们使用自定义配置会比较方便。比如我们需要在生产环境模板中引入第三方统计脚本</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">/* vue.config.js */</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    ...</span><br><span class="line">    </span><br><span class="line">    pages: utils.setPages(&#123;</span><br><span class="line">        addScript() &#123;</span><br><span class="line">            <span class="keyword">if</span> (process.env.NODE_ENV === <span class="string">'production'</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="string">`</span></span><br><span class="line"><span class="string">                    &lt;script src="https://s95.cnzz.com/z_stat.php?id=xxx&amp;web_id=xxx" language="JavaScript"&gt;&lt;/script&gt;</span></span><br><span class="line"><span class="string">                `</span></span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> <span class="string">''</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;),</span><br><span class="line">    </span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>然后在页面模板中通过 <code>htmlWebpackPlugin.options</code> 获取自定义配置对象并进行输出</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&lt;% if(htmlWebpackPlugin.options.addScript)&#123; %&gt;</span><br><span class="line">    &lt;%= htmlWebpackPlugin.options.addScript() %&gt;</span><br><span class="line">&lt;%&#125;%&gt;</span><br></pre></td></tr></table></figure>
<p>同时你也可以针对个别模板进行配置，比如我想只在 Index 单页中添加统计脚本，在 Page1 单页中添加其他脚本，那么你可以给 addScript 传入标识符来进行判断输出，比如</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&lt;% if(htmlWebpackPlugin.options.addScript)&#123; %&gt;</span><br><span class="line">    &lt;%= htmlWebpackPlugin.options.addScript(&apos;index&apos;) %&gt;</span><br><span class="line">&lt;%&#125;%&gt;</span><br></pre></td></tr></table></figure>
<p>同时为 <code>addScript</code> 方法添加参数 <code>from</code>：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">addScript(<span class="keyword">from</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (process.env.NODE_ENV === <span class="string">'production'</span>) &#123;</span><br><span class="line">        <span class="keyword">let</span> url = <span class="string">"https://xxx"</span>;</span><br><span class="line">    </span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">from</span> === <span class="string">'index'</span>) &#123;</span><br><span class="line">            url = <span class="string">"https://s95.cnzz.com/z_stat.php?id=xxx&amp;web_id=xxx"</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> <span class="string">`</span></span><br><span class="line"><span class="string">            &lt;script src=<span class="subst">$&#123;url&#125;</span> language="JavaScript"&gt;&lt;/script&gt;</span></span><br><span class="line"><span class="string">        `</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="string">''</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2019/06/01/vue-muti-page-config/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2019/06/01/vue-opz/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
